import base64
import json
import pickle

from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from goods.models import SKU


class CartsView(View):
    def post(self, request):

        # 接收参数
        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': 'sku_id 错误'})

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': 'count 错误'})

        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({'code': 400, 'errmsg': 'selected 错误'})

        # 判断用户是否登录
        if request.user.is_authenticated:

            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            # 新增购物车数据
            pl.hincrby('carts_%s' % request.user.id, sku_id, count)
            # 新增选中的状态
            pl.sadd('selected_%s' % request.user.id, sku_id)

            # 执行管道
            pl.execute()

            return JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})

        else:
            # 用户未登录，操作cookie购物车
            cookies_cart = request.COOKIES.get('carts')

            # cookies存在
            if cookies_cart:
                # 解密, 获取购物车商品
                cart_dict = pickle.loads(base64.b64decode(cookies_cart))
            else:
                # cookies不存在
                cart_dict = {}

            # 判断要添加的购物车商品 是否在购物车商品列表
            if sku_id in cart_dict:
                # 在, 数据累计
                count += cart_dict[sku_id]['count']

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 加密
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('carts', cart_data)

            return response

    def get(self, request):

        # 判断用户是否登陆
        if request.user.is_authenticated:
            # 登陆用户 操作redis
            # 连接redis
            redis_conn = get_redis_connection('carts')

            # 获取当前用户购物车数据
            item_dict = redis_conn.hgetall('carts_%s' % request.user.id)
            # 获取当前用户购物车数据选中状态
            cart_selected = redis_conn.smembers('selected_%s' % request.user.id)

            # 整理数据
            cart_dict = {}

            for sku_id, count in item_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected,
                }

        else:
            # 未登陆, 操作cookies
            cookies_cart = request.COOKIES.get('carts')

            if cookies_cart:
                # 解密
                cart_dict = pickle.loads(base64.b64decode(cookies_cart.encode()))
            else:
                cart_dict = {}

        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)

        cart_skus = []

        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict[sku.id]['count'],
                'selected': cart_dict[sku.id]['selected'],
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * cart_dict[sku.id]['count']
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})

    def put(self, request):
        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': 'sku_id 错误'})

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': 'count 错误'})

        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({'code': 400, 'errmsg': 'selected 错误'})

        user = request.user
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_conn = get_redis_connection('carts')

            pl = redis_conn.pipeline()

            # 覆盖数量
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 判断是否勾选
            if selected:
                # 勾选,添加
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                # 未勾选,删除
                pl.srem('selected_%s' % user.id, sku_id)

            pl.execute()

            # 构建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
            }

            return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})

        else:

            # 用户未登录，修改cookie购物车
            cookies_cart = request.COOKIES.get('carts')

            if cookies_cart:
                cart_dict = pickle.loads(base64.b64decode(cookies_cart.encode()))
            else:
                cart_dict = {}

            cart_dict[sku_id] = {
               'count': count,
               'selected': selected
            }

            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 构建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
            }

            response = JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})

            response.set_cookie('carts', cart_data)

            return response

    def delete(self, request):
        sku_id = json.loads(request.body.decode()).get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户登录，操作redis购物车
            redis_conn = get_redis_connection('carts')

            pl = redis_conn.pipeline()

            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)

            pl.execute()

            return JsonResponse({'code': 0, 'errmsg': 'ok'})

        else:
            # 用户未登录，删除cookie购物车
            # 用户未登录，修改cookie购物车
            cookies_cart = request.COOKIES.get('carts')

            if cookies_cart:
                cart_dict = pickle.loads(base64.b64decode(cookies_cart.encode()))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 加密
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('carts', cart_data)

            return response


class CartSelectAllView(View):

    def put(self, request):
        # 接收参数
        selected = json.loads(request.body.decode()).get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({'code': 400, 'errmsg': 'selected错误'})

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')

            pl = redis_conn.pipeline()

            # 获取当前用户所有购物车数据
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            # 获取字典数据全部key
            sku_ids = item_dict.keys()

            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *sku_ids)
            else:
                # 全不选
                redis_conn.srem('selected_%s' % user.id, *sku_ids)

            pl.execute()

            return JsonResponse({'code': 0, 'errmsg': 'ok'})

        else:
            # 用户已登录，操作cookie购物车
            cookies_cart = request.COOKIES.get('carts')

            if cookies_cart:
                cart_dict = pickle.loads(base64.b64decode(cookies_cart.encode()))

                for sku_id in cart_dict:
                    # 修改
                    cart_dict[sku_id]['selected'] = selected

                # 加密
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

                response = JsonResponse({'code': 0, 'errmsg': 'ok'})

                response.set_cookie('carts', cart_data)

                return response


class CartsSimpleView(View):
    def get(self, request):

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询 Redis 购物车
            redis_conn = get_redis_connection('carts')

            # 查询 Redis 购物车
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            # 将 redis 中的两个数据统一格式，跟 cookie 中的格式一致，方便统一查询
            cart_dict = {}

            for sku_id, count in item_dict.items():
                # print(sku_id, count)
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }

        else:
            # 用户未登录，查询 cookie 购物车
            cookies_cart = request.COOKIES.get('carts')

            if cookies_cart:
                cart_dict = pickle.loads(base64.b64decode(cookies_cart.encode()))

            else:
                cart_dict = {}

        # 构造简单购物车 JSON 数据
        '''
        [{
         "id": 1,
         "name": "Apple MacBook Pro 13.3英寸笔记本 银色",
         "count": 1,
         "default_image_url": "http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrPB4GAWkTlAAGuN6wB9fU4220429"
        },
        {}....
        ]
        '''

        cart_skus = []

        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)

        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image_url
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})







